<?php

// User类
class UserAction extends Action
{

    public function index($status = '', $startDate = '', $endDate = '', $order = 'id', $orderBy = 'desc', $start = 0, $limit = 25)
    {

        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $customerId = Session::$user["customerId"];
        $isApiAuth = Session::$user['isApiAuth'];
// 		Session::switchCustomer(0);

        $userModel = D('user');

        if ($status == "") {
        } else if ($status == "subscribe") {
            $condition['user.status'] = array('eq', $status);

            if ($startDate == "") {
            } else {
                $condition['user.subscribeTime'] = array('between', array($startDate, $endDate));
            }
        } else if ($status == "unsubscribe") {
            $condition['user.status'] = array('eq', $status);

            if ($startDate == "") {
            } else {
                $condition['user.unsubscribeTime'] = array('between', array($startDate, $endDate));
            }
        }


        if ($isApiAuth) {//有高级接口
// 			$condition['uni.customerId'] = array('eq',$customerId);
// 			$condition['uni.customerId'] = array(array('eq',$customerId),array('exp',' is NULL'),"or");

            $arr = $userModel->alias('user')
                ->join('LEFT JOIN wx_' . $customerId . '_user_weixin_info winfo on winfo.openid = user.userName')
                ->join('LEFT JOIN wx_' . $customerId . '_user_info uinfo on uinfo.fromUserName = user.userName')
                ->where($condition)
                ->field('user.*,winfo.openid,winfo.subscribe,winfo.nickname,winfo.sex,winfo.language,winfo.city,winfo.province,winfo.country,winfo.headimgurl,winfo.subscribe_time,uinfo.fullName,uinfo.phone,uinfo.picUrl')
// 			->field('user.*,winfo.*,uinfo.fullName,uinfo.phone,uinfo.picUrl')
                ->order("user.$order $orderBy")
                ->limit("$start,$limit")
                ->select();

            $count = $userModel->alias('user')
                ->join('LEFT JOIN wx_' . $customerId . '_user_weixin_info winfo on winfo.openid = user.userName')
                ->join('LEFT JOIN wx_' . $customerId . '_user_info uinfo on uinfo.fromUserName = user.userName')
                ->where($condition)
                ->count();

        } else {
// 			$condition['uni.customerId'] = array('eq',$customerId);

            $arr = $userModel->alias('user')
                ->join('LEFT JOIN wx_' . $customerId . '_user_info uinfo on uinfo.fromUserName = user.userName')
                ->where($condition)
                ->field('user.*,uinfo.fullName,uinfo.phone,uinfo.picUrl')
                ->order("user.$order $orderBy")
                ->limit("$start,$limit")
                ->select();

            $count = $userModel->alias('user')
                ->join('LEFT JOIN wx_' . $customerId . '_user_info uinfo on uinfo.fromUserName = user.userName')
                ->where($condition)
                ->count();
        }

        if ($arr) {
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode(code_success);
        }
    }

    //获取当前登录账户的公众号用户列表
    public function getUserList($nickname = '', $userType = '', $source = '', $ticket = '', $qrcodename = '', $groupId = null, $order = 'id', $orderBy = 'desc', $start = 0, $limit = 25)
    {
        $retVal = Session::init();

        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userListModel = M('user');
        //用户来源的添加
        $customerId = Session::$user["customerId"];
        $where = '';
        if (trim($nickname) != '') {
            $where['wxinfo.nickname'] = array('like', '%' . $nickname . '%');
        }
        if (trim($source) == 'interest') {
            $where['user.status'] = array('eq', 'subscribe');
        } else if (trim($source) == 'qrcode') {
            $where['user.status'] = array('eq', 'scansubscribe');
        } else if (trim($source) == 'share') {
            $where['user.status'] = array('eq', 'sharesubscribe');
        } else if (trim($source) == 'unsubscribe') {
            $where['user.status'] = array('eq', 'unsubscribe');
        } else if (trim($source) == 'care') {
            $where['user.status'] = array('in', 'subscribe,scansubscribe');
        }
        if (trim($ticket) != '') {
            Session::switchCustomer(0);
            $qrcode = M('qrcode');
            Session::switchCustomer($customerId);
            $ticketwhere['ticket'] = array('eq', $ticket);
            $qrcodearr = $qrcode->alias('qrcode')->distinct(true)->field("fromUserName")->join("left JOIN wx_qrcode_scan_log  scanqrcode on scanqrcode.sceneId = qrcode.sceneId")->where($ticketwhere)->select();
            foreach ($qrcodearr as $key => $value) {
                $ticketsUserName .= $value['fromUserName'] . ',';
            }

            $ticketsUserName = substr($ticketsUserName, 0, strlen($ticketsUserName) - 1);
            $where['user.userName'] = array('in', $ticketsUserName);
            //echo $qrcode->getLastSql();
        }
        if (trim($qrcodename) != '') {
            Session::switchCustomer(0);
            $qrcode = M('qrcode');
            $qrcodewhere['name'] = array('like', '%' . $qrcodename . '%');
            $qr = $qrcode->where($qrcodewhere)->find();

            $where['ticket'] = array('eq', $qr['ticket']);
            Session::switchCustomer($customerId);
        }
        if (trim($userType) == 'active') {
            $where['user.lastTime'] = array('egt', date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 2, date("Y"))));
            $order = 'lastTime';
        }
        isset($groupId) && $groupId ? $where['_string'] = "find_in_set($groupId,user.groupId)" : "";
        $result = $userListModel->alias('user')
            ->join("INNER JOIN wx_" . $customerId . "_user_weixin_info  wxinfo on wxinfo.openid = user.userName ")
            ->join("left JOIN wx_" . $customerId . "_user_weixin_group c on find_in_set(c.group_id,user.groupId)")
            ->field("user.*, wxinfo.*, group_concat(c.group_name) as group_name")
            ->group('user.id')
            ->where($where)->order("user.$order $orderBy")->limit($start, $limit)->select();

        //echo $userListModel->getLastSql();

        $count = $userListModel->alias('user')
            ->join("INNER JOIN wx_" . $customerId . "_user_weixin_info  wxinfo on wxinfo.openid = user.userName")
            ->where($where)->count();
        if ($result) {
            Output::instance()->objArray($result, $count);
        } else {
            Output::instance()->resultCode();
        }
    }


    /**
     * 新平台,获取当前登录账户的公众号用户列表
     * @param string $nickname /搜索昵称
     * @param string $mediaId /自媒体id
     * @param string $userType /粉丝类型:活跃
     * @param string $source /关注形式
     * @param string $ticket /二维码标识,页面暂未使用
     * @param string $qrcodename /二维码名称,页面暂未使用
     * @param null $groupId /分组id
     * @param string $order /排序规则
     * @param string $orderBy /排序字段
     * @param int $start /起始
     * @param int $limit /偏移量
     */
    public function getNewUserList($nickname = '', $mediaId = 0, $userType = '', $source = '', $ticket = '',
                                   $qrcodename = '', $groupId = null, $order = 'id', $orderBy = 'desc', $start = 0, $limit = 25)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userListModel = M('user');
        //用户来源的添加
        $customerId = Session::$user["customerId"];
        $where = '';
        if (trim($nickname) != '') {
            $where['wxinfo.nickname'] = array('like', '%' . $nickname . '%');
        }
        if (trim($source) == 'interest') {
            $where['user.status'] = array('eq', 'subscribe');
        } else if (trim($source) == 'qrcode') {
            $where['user.status'] = array('eq', 'scansubscribe');
        } else if (trim($source) == 'share') {
            $where['user.status'] = array('eq', 'sharesubscribe');
        } else if (trim($source) == 'unsubscribe') {
            $where['user.status'] = array('eq', 'unsubscribe');
        } else if (trim($source) == 'care') {
            $where['user.status'] = array('in', 'subscribe,scansubscribe,sharesubscribe');
        }
        if (trim($ticket) != '') {
            //暂时未使用
            Session::switchCustomer(0);
            $qrcode = M('qrcode');
            Session::switchCustomer($customerId);
            $ticketwhere['ticket'] = array('eq', $ticket);
            $qrcodearr = $qrcode->alias('qrcode')->distinct(true)->field("fromUserName")
                ->join("left JOIN wx_qrcode_scan_log  scanqrcode on scanqrcode.sceneId = qrcode.sceneId")
                ->where($ticketwhere)
                ->select();
            $ticketsUserName = '';
            foreach ($qrcodearr as $key => $value) {
                $ticketsUserName .= $value['fromUserName'] . ',';
            }

            $ticketsUserName = substr($ticketsUserName, 0, strlen($ticketsUserName) - 1);
            $where['user.userName'] = array('in', $ticketsUserName);
        }
        if (trim($qrcodename) != '') {
            //暂时未使用
            Session::switchCustomer(0);
            $qrcode = M('qrcode');
            $qrcodewhere['name'] = array('like', '%' . $qrcodename . '%');
            $qr = $qrcode->where($qrcodewhere)->find();

            $where['ticket'] = array('eq', $qr['ticket']);
            Session::switchCustomer($customerId);
        }
        if (trim($userType) == 'active') {
            $where['user.lastTime'] = array('egt', date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 2, date("Y"))));
            $order = 'lastTime';
        }

        if ($groupId) {
            $where['_string'] = "find_in_set($groupId,user.groupId)";
        }
        $where['user.mediaId'] = $mediaId;
        $result = $userListModel->alias('user')
            ->join("INNER JOIN wx_" . $customerId . "_user_weixin_info  wxinfo on wxinfo.openid = user.userName ")
            ->join("LEFT JOIN wx_" . $customerId . "_user_group_list ugl on ugl.fansId = user.userName ")
            ->field("user.*, wxinfo.*, group_concat(ugl.groupId) as group_id")
            ->group('user.id')
            ->where($where)->order("user.$order $orderBy")->limit($start, $limit)->select();
        /*echo '<pre>';
        var_dump($userListModel->getLastSql());
        echo '<pre>';exit;*/
        if (!$result) {
            Output::instance()->object([
                'total'=>0,
                'results'=>[]
            ]);
            return;
        }
        //拼接分组信息
        $groupList = self::getUserGroup(true, $mediaId);
        $resultDate = $groups = [];
        if ($groupList) {
            foreach ($groupList as $groupKey => $value) {
                $groups[$value['group_id']] = $value;
            }
        }

        foreach ($result as $key => $val) {
            $groupInfo = [];
            if ($val['groupId']) {
                $groupIds = explode(',', $val['groupId']);
                foreach ($groupIds as $k => $v) {
                    $groupInfo[$v] = $groups[$v]['group_name'] ? $groups[$v]['group_name'] : '';
                }
            }
            $val['groupInfo'] = $groupInfo;
            $resultDate[$key] = $val;
        }

        $count = $userListModel->alias('user')
            ->join("INNER JOIN wx_" . $customerId . "_user_weixin_info  wxinfo on wxinfo.openid = user.userName")
            ->where($where)->count();
        Output::instance()->objArray($resultDate, $count);

    }

    //批量删除标签
    public function deletedUersTag($idlist, $togroupid)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $userModel = M("user_weixin_info");
        $user = M("user");
        $userInfo = $userModel->where('id in (' . $idlist . ')')->field('GROUP_CONCAT(openid) as openidlist')->find();
        $openidlist = explode(',', $userInfo['openidlist']);
        $result = WeixinApi::deletedUsersTag($openidlist, $togroupid);
        $result = json_decode($result, true);
        if ($result['errcode']) {
            Output::instance()->resultCode($result['errcode'], $result['errmsg']);
        } else {
            $where['userName'] = array('in', $openidlist);
            $user->where($where)->setField("groupId", null);
        }
        Output::instance()->resultCode(code_success);
    }

    /**
     * 对个人标签进行操作, 包含删除以及增加
     * @param $mediaId /自媒体id
     * @param $id /userId
     * @param $toGroupIds /将要取消组ids
     */
    public function deletedNewUersTag($mediaId = 0, $id, $toGroupIds='')
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $user_table = M("user");
        $userModel = M("user_weixin_info");
        $userGroup_table = M("user_group_list");
        //获取用户存在或者不存在的组
        if(!$toGroupIds){
            $toGroupIds = [];
        }else{
            $toGroupIds = explode(',', $toGroupIds);
        }
        $info = $user_table->where(['id'=>$id])->field('userName,status')->find();
        $openid = $info['userName'];
        if(!$openid){
            Output::instance()->object([
               'code'=>-1,
                'msg'=>'用户信息错误,请刷新粉丝重试'
            ]);
            return;
        }

        if($info['status'] == 'unsubscribe'){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'用户已取消关注,暂无法操作'
            ]);
            return;
        }
        $groupIdList = $userGroup_table->where(['fansId' => $openid, 'mediaId'=>$mediaId])->getField('groupId', true);
        $groupIdList = $groupIdList?$groupIdList:[];
        $diffArr = array_merge(array_diff($toGroupIds, $groupIdList),array_diff($groupIdList,$toGroupIds)); // [1,4,5] [1,2,3] 差异[2,3,4,5]

        if(count($diffArr)<1){
            Output::instance()->resultCode(code_success);
            return;
        }
        foreach ($diffArr as $key => $val) {
            if (in_array($val, $groupIdList)) {
                /*存在就移除*/
                M()->startTrans();
                //将本地关联记录删除
                $where['fansId'] = $openid;
                $where['groupId'] = $val;
                $where['mediaId'] = $mediaId;
                $delRet = $userGroup_table->where($where)->delete();
                if(!$delRet){
                    Log::write('jie-0'.$userGroup_table->getLastSql());
                    M()->rollback();
                    Output::instance()->object([
                        'code'=>1,
                        'msg'=>'删除关联失败'
                    ]);
                    return;
                }
                //更新wx_x_user表中groupId
                $groupId = $user_table->where(['id' => $id])->getField('groupId');
                if($groupId){
                    $groupIds = explode(',', $groupId);
                    if (in_array($val, $groupIds)) {
                        $groupIdkey = array_search($val, $groupIds);
                        unset($groupIds[$groupIdkey]);
                        $newGroupId = count($groupIds) > 0 ? join(',', $groupIds) : '';
                        $groupIdRet = $user_table->where(['id' => $id])->setField('groupId', $newGroupId);
                        if (!$groupIdRet) {
                            Log::write('jie-1'.$user_table->getLastSql());
                            M()->rollback();
                            Output::instance()->object([
                                'code'=>1,
                                'msg'=>'更新用户分组失败'
                            ]);
                            return;
                        }
                    }
                }
                $result = WeixinApi::deletedUsersTag($openid, $val, $mediaId);
                $result = json_decode($result, true);
                if ($result['errcode']) {
                    M()->rollback();
                    Output::instance()->resultCode($result['errcode'], $result['errmsg']);
                    return;
                }
                M()->commit();
                /*if (!$groupId) {
                    continue;
                }
                $groupIds = explode(',', $groupId);
                if (!in_array($val, $groupIds)) {
                    continue;
                }
                $groupIdkey = array_search($val, $groupIds);
                unset($groupIds[$groupIdkey]);
                $newGroupId = count($groupIds) > 0 ? join(',', $groupIds) : '';
                $groupIdRet = $user_table->where(['id' => $id])->setField('groupId', $newGroupId);
                if (!$groupIdRet) {
                    Output::instance()->resultCode(code_sql_error);
                    return;
                }*/
            } else {
                /*不存在添加*/
                M()->startTrans();
                $addUserGroupData = [];
                $addUserGroupData['mediaId'] = $mediaId;
                $addUserGroupData['fansId'] = $openid;
                $addUserGroupData['groupId'] = $val;
                if (!$userGroup_table->add($addUserGroupData)) {
                    M()->rollback();
                    Log::write('jie-2'.$userGroup_table->getLastSql());
                    Output::instance()->object([
                        'code'=>-1,
                        'msg'=>'保存关联失败'
                    ]);
                    return;
                }

                //更新wx_x_user表groupId
                $groupId = $user_table->where(['id' => $id])->getField('groupId');
                $newGroupId = '';
                if ($groupId) {
                    $groupIds = explode(',', $groupId);
                    if (!in_array($val, $groupIds)) {
                        $newGroupId = $groupId . ',' . $val;
                    }
                } else {
                    $newGroupId = $val;
                }

                $groupIdRet = $user_table->where(['id' => $id])->setField('groupId', $newGroupId);
                R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $userGroup_table->getLastSql(),
                    '批量移动粉丝到某些小组,更新公众平台以及本地粉丝与组的关联'));
                if (!$groupIdRet) {
                    Log::write('jie-1'.$user_table->getLastSql());
                    M()->rollback();
                    Output::instance()->object([
                        'code'=>1,
                        'msg'=>'更新分组失败'
                    ]);
                    return;
                }
                $result = WeixinApi::setUsersTag($openid, $val, $mediaId);
                $result = json_decode($result, true);
                if ($result['errcode']) {
                    M()->rollback();
                    Output::instance()->resultCode($result['errcode'], $result['errmsg']);
                    return;
                }
                M()->commit();
            }
        }
        Output::instance()->resultCode(code_success);
    }

    //批量移动分组
    public function removeUsersToGroup($idlist, $togroupid)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $user = M("user");
        $userModel = M("user_weixin_info");
        if (!$idlist) {
            Output::instance()->resultCode(code_sql_error);
        }
        $userInfo = $userModel->alias("a")
            ->join("inner join wx_" . $cid . "_user b on a.openid=b.userName")
            ->field("group_concat(b.groupId) as groupIds")
            ->where("a.id in (" . $idlist . ")")
            ->find();
        $groupIds = array_unique(explode($userInfo['groupIds'], ","));
        $openids = $userModel->where('id in (' . $idlist . ')')->getField("openid", true);
        foreach ($groupIds as $key => $value) {
            WeixinApi::deletedUsersTag($openids, $value);
        }
        $result = WeixinApi::setUsersTag($openids, $togroupid);
        $result = json_decode($result, true);
        if ($result['errcode']) {
            Output::instance()->resultCode($result['errcode'], $result['errmsg']);
            return;
        } else {
            $where['userName'] = array("in", $openids);
            $result = $user->where($where)->setField("groupId", $togroupid);
            if ($result) {
                Output::instance()->resultCode(code_success);
            } else {
                Output::instance()->resultCode(code_sql_error);
            }
        }
    }

    /**
     * 批量移动分组,在之前的分组基础上加上新的分组
     * @param $mediaId /自媒体id
     * @param $idList /userIds
     * @param $toGroupId /组id
     * @param $return /是否将结果返回
     */
    public function removeNewUsersToGroup($mediaId = 0, $idList, $toGroupId, $return=0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        $user_table = M('user');
        $userGroup_table = M("user_group_list");
        $userModel = M("user_weixin_info");
        if (!$idList) {
            Output::instance()->resultCode(code_sql_error);
        }

        $openIds = $userModel->where('userId in (' . $idList . ')')->getField("openid", true);

        $groupIdArr = explode(',', $toGroupId);
        foreach ($groupIdArr as $k => $groupIdVal) {
            //保存微信端数据
            M()->startTrans();
            $addDate = [];
            foreach ($openIds as $key => $val) {
                //更新wx_x_user表中groupId
                $groupId = $user_table->where(['userName' => $val])->getField('groupId');
                $newGroupId = '';
                if ($groupId) {
                    $groupIds = explode(',', $groupId);
                    if (!in_array($groupIdVal, $groupIds)) {
                        $newGroupId = $groupId . ',' . $groupIdVal;
                    }
                } else {
                    $newGroupId = $groupIdVal;
                }
                if ($newGroupId) {
                    $groupIdRet = $user_table->where(['userName' => $val])->setField('groupId', $newGroupId);
                    R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $userGroup_table->getLastSql(),
                        '批量移动粉丝到相关的小组,更新粉丝与组的关联关系'));
                    if (!$groupIdRet) {
                        M()->rollback();
                        if($return){
                            return false;
                        }
                        Output::instance()->resultCode(code_sql_error);
                        return;
                    }
                }

                //添加新的关联信息
                if ($userGroup_table->where(['fansId' => $val, 'groupId' => $groupIdVal, 'mediaId' => $mediaId])->find()) {
                    continue;
                }
                $addDate[$key]['fansId'] = $val;
            }
            if (count($addDate) > 0) {
                $sql = 'insert into wx_' . $cid . '_user_group_list (`groupId`,`fansId`,`mediaId`) VALUES ';
                foreach ($addDate as $key => $val) {
                    $sql .= "(" . $groupIdVal . ",'" . $val['fansId'] . "'," . $mediaId . "),";
                }
                $sql = trim($sql, ',') . ';';
                $result = M()->execute($sql);
                if (!$result) {
                    M()->rollback();
                    if($return){
                        return false;
                    }
                    Output::instance()->resultCode(code_sql_error);
                    return;
                }
            }

            $result = WeixinApi::setUsersTag($openIds, $groupIdVal, $mediaId);
            $result = json_decode($result, true);
            if ($result['errcode']) {
                M()->rollback();
                if($return){
                    return false;
                }
                Output::instance()->resultCode($result['errcode'], $result['errmsg']);
                return;
            }
            M()->commit();
        }
        if($return){
            return true;
        }
        Output::instance()->resultCode(code_success);
    }

    //设置改账号自动分组
    public function setAutoGroup($isAutoGroup = 0, $mediaId = 0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        /**
         * LLyeap_wx_customer修改
         */
        /***** LLyeap_delete *****/
//		$customerModel = M("customer");
        $IndMediaInfo_Model = D('ind_media_info');
        Session::switchCustomer($customerId);
//        $condition['id']=array('eq',$customerId);
        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['cid' => $customerId, 'id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['cid' => $customerId, 'isDefault' => 1];
        }
        $data['isAutoGroup'] = $isAutoGroup;
//		$result = $customerModel->where($condition)->save($data);
        $result = $IndMediaInfo_Model->where($where_info)->save($data);
        if ($result !== false) {
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    //获得账号分组配置
    public function getAutoGroup($mediaId = 0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        /**
         * LLyeap_wx_customer修改
         */
        /***** LLyeap_delete *****/
//		$customerModel = M("customer");
        $IndMediaInfo_Model = D('ind_media_info');
        Session::switchCustomer($customerId);
//		$condition['id']=array('eq',$customerId);
//		$result = $customerModel->where($condition)->find();

        if ($mediaId > 0) { // 如果拿到了$mediaId, 则通过id来筛选
            $where_info = ['cid' => $customerId, 'id' => $mediaId];
        } else {        // 如果没有$mediaId, 则拿这个cid下默认的账号, 即default = 1的, 只有一个
            $where_info = ['cid' => $customerId, 'isDefault' => 1];
        }
        $result = $IndMediaInfo_Model->where($where_info)->find();
        Output::instance()->object($result);
    }

    /**
     * 获取相对应的自媒体所有用户分组
     * @param int $self
     * @param int $mediaId
     * @return mixed|void
     */
    public function getUserGroup($self = 0, $mediaId = 0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $usergroup = M("user_weixin_group");
        if($mediaId){
            $group = $usergroup->where(['mediaId'=>$mediaId])->select();
        }else{
            $group = $usergroup->select();
        }
        if ($self) {
            return $group;
        }
        $result['group'] = $group;
        $result['code'] = 0;
        Output::instance()->object($result);
    }

    public function delUserGroup($ids)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $usergroup = M("user_weixin_group");

        $arr_ids = explode(',', $ids);
        $res = $usergroup->where(['id' => ['IN', $arr_ids]])->delete();

        $Out = [
            'code' => 0,
            'msg' => '删除成功',
            'data' => [
                'res' => $res
            ]
        ];
        Output::instance()->object($Out);
    }

    /**
     * 拉取官方平台用户数据并刷新本地用户列表
     * @$mediaId 多媒体id
     */
    public function freshenUserList($mediaId)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        //设置执行时间无限
        if (ini_get('max_execution_time')) {
            ini_set('max_execution_time', '0');
        }

        if($mediaId == 0){
            Output::instance()->object(array(
                'code' => -1,
                'msg' => '自媒体id有误',
                'data' => ''
            ));
            return;
        }

        //刷新用户组
        $refreshRet = UserGroupAction::refreshGroup(true, $mediaId);
        if (!$refreshRet) {
            return;
        }

        //将从微信公众号获取到的粉丝数组更新到现有的wx_3_user表和wx_3_user_weixin_info表中去,如果数据存在更新,不存在新增
        $cid = Session::$user['customerId'];
        $wxInfoTable = M('user_weixin_info');
        $userModel = M('user');
        $userGroup = M('user_group_list');
        //清空用户和组的关联关系
        $delUserGroupRet = $userGroup->where(array('mediaId' => $mediaId))->delete();
        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_delete, $userGroup->getLastSql(),
            '将微信公众号平台的粉丝信息(粉丝信息,分组信息)刷新到本地'));
        if (!is_numeric($delUserGroupRet)) {
            Output::instance()->object(array(
                'code' => -1,
                'msg' => '清空用户关联组失败',
                'data' => ''
            ));
            return;
        }

        $accessToken = WeixinApi::getAccessToken(true,null,null,$mediaId);
        //获取公众号粉丝信息
        $bool = WeixinApi::getCustomerWxUserList($accessToken);
        if(!$bool){
            Output::instance()->object(array(
                'code' => -1,
                'msg' => '拉取粉丝失败',
                'data' => ''
            ));
            return;
        }
        $redis = new Redis();
        $redis->connect(C('REDIS_HOST'), C('REDIS_PORT'));
        $redis->auth(C('REDIS_PASSWORD'));
        Log::write('jie---user'.$redis->lLen($accessToken));
        $bool = true;
        while ($bool) {
            $v = unserialize($redis->rPop($accessToken));
            if (!$v) {
                $bool = false;
                continue;
            }
            if($v->openid == null){
                continue;
            }
            M()->startTrans();
            //保存user表
            $where = [];
            $where['userName'] =  $v->openid;
            $where["mediaId"] = [["eq", 0], ["eq", $mediaId], "or"];
            $user = $userModel->where($where)->find();

            if ($user == null) {
                $userId = $userModel->data(array(
                    'userName' => $v->openid,
                    'openid' => $v->openid,
                    'profileUrl' => $v->headimgurl,
                    'role' => 'user',
                    'subscribeTime' => date('Y-m-d H:i:s', $v->subscribe_time),
                    'status' => 'subscribe',
                    'groupId' => $v->tagid_list ? join(',', $v->tagid_list) : '',
                    'mediaId' => $mediaId
                ))->add();
                if ($userId < 1) {
                    Log::write('保存用户表失败-----------222' .$userModel->getDbError());
                    M()->rollback();
                    continue;
                    //throw new Exception('保存用户表失败|errorInfo:'.$userModel->getDbError());
                }
            } else {
                //已关注
                $data = array();
                if ($user['status'] == 'subscribe' || $user['status'] == 'scansubscribe' || $user['status'] == 1) {
                    $data = array(
                        'userName' => $v->openid,
                        'openid' => $v->openid,
                        'profileUrl' => $v->headimgurl,
                        'subscribeTime' => date('Y-m-d H:i:s', $v->subscribe_time),
                        'groupId' => $v->tagid_list ? join(',', $v->tagid_list) : '',
                        'mediaId' => $mediaId
                    );
                }
                //未关注
                if ($user['status'] == 'sharesubscribe' || $user['status'] == 'unsubscribe') {
                    $data = array(
                        'userName' => $v->openid,
                        'openid' => $v->openid,
                        'profileUrl' => $v->headimgurl,
                        'status' => 'subscribe',
                        'subscribeTime' => date('Y-m-d H:i:s', $v->subscribe_time),
                        'groupId' => $v->tagid_list ? join(',', $v->tagid_list) : '',
                        'mediaId' => $mediaId
                    );
                }
                $result = $userModel->where(array('userName' => $v->openid))->save($data);

                $userId = $user['id'];
                if ($result === false) {
                    Log::write('更新用户信息失败------------333' . $userModel->getDbError());
                    M()->rollback();
                    continue;
                    //throw new Exception('更新用户信息失败'.'|errorInfo:'.$userModel->getDbError().'会员数量:'.$redis->lLen($accessToken));
                }
            }

            //保存wx_3_user_weixin_info信息表
            $wxInfo = $wxInfoTable->where(array('openid' => $v->openid))->find();
            if ($wxInfo == null) {
                $result = $wxInfoTable->data(array(
                    'subscribe' => $v->subscribe,
                    'openid' => $v->openid,
                    'nickname' => $v->nickname,
                    'sex' => $v->sex,
                    'city' => $v->city,
                    'country' => $v->country,
                    'province' => $v->province,
                    'language' => $v->language,
                    'headimgurl' => $v->headimgurl,
                    'subscribe_time' => date('Y-m-d H:i:s', $v->subscribe_time),
                    'unionid' => $v->unionid ? $v->unionid : '',
                    'userId' => $userId
                ))->add();
                if ($result < 1) {
                    Log::write('保存用户微信信息失败------------444' . $wxInfoTable->getDbError());
                    M()->rollback();
                    continue;
                    //throw new Exception('保存用户微信信息失败'.'|errorInfo:'.$wxInfoTable->getDbError());
                }
            } else {
                $result = $wxInfoTable->where(array('openid' => $v->openid))->save(array(
                    'subscribe' => $v->subscribe,
                    'nickname' => $v->nickname,
                    'sex' => $v->sex,
                    'city' => $v->city,
                    'country' => $v->country,
                    'province' => $v->province,
                    'language' => $v->language,
                    'headimgurl' => $v->headimgurl,
                    'subscribe_time' => date('Y-m-d H:i:s', $v->subscribe_time),
                    'unionid' => $v->unionid ? $v->unionid : '',
                    'userId' => $userId
                ));
                if ($result === false) {
                    Log::write('更新用户信息失败------------555' . $wxInfoTable->getDbError());
                    M()->rollback();
                    continue;
                }
            }

            //保存用户和组的关联表
            if (count($v->tagid_list) > 0) {
                $tagIds = $v->tagid_list;
                $ugl = [];
                $ugl['mediaId'] = $mediaId;
                $ugl['fansId'] = $v->openid;
                $ugl['groupId'] = ['in', $tagIds];
                M('user_group_list')->where($ugl)->delete();
                $sql = 'INSERT INTO `wx_'.$cid.'_user_group_list` (`mediaId`, `groupId`, `fansId`) VALUES';
                foreach ($tagIds as $k => $val) {
                    $sql .= "(" . $mediaId . "," . $val . ",'" . $v->openid . "'),";
                }
                $sql = trim($sql, ',') . ';';
                $result = M()->execute($sql);
                if (!$result) {
                    Log::write('会员管理刷新------------555' . M()->getDbError());
                    M()->rollback();
                    continue;
                }
            }
            M()->commit();
        }
        //删除队列
        $redis->delete($accessToken);
        Output::instance()->resultCode(code_success);
    }

    public function getUserByFromUserName($fromUserName)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $customerId = Session::$user["customerId"];
        $isApiAuth = Session::$user['isApiAuth'];

        $userModel = D('user');
        $condition['user.userName'] = $fromUserName;

        if ($isApiAuth) {
            $result = $userModel->alias('user')
                ->join('LEFT JOIN wx_' . $customerId . '_user_weixin_info winfo on winfo.openid = user.userName')
                ->join('LEFT JOIN wx_' . $customerId . '_user_info uinfo on uinfo.fromUserName = user.userName')
                ->where($condition)
                ->field('user.*,winfo.openid,winfo.subscribe,winfo.nickname,winfo.sex,winfo.language,winfo.city,winfo.province,winfo.country,winfo.headimgurl,winfo.subscribe_time,uinfo.fullName,uinfo.phone,uinfo.picUrl')
                ->find();
        } else {
            $result = $userModel->alias('user')
                ->join('LEFT JOIN wx_' . $customerId . '_user_info uinfo on uinfo.fromUserName = user.userName')
                ->where($condition)
                ->field('user.*,uinfo.fullName,uinfo.phone,uinfo.picUrl')
                ->find();
        }

// 		echo $userModel->getLastSql();

        if ($result) {
            Output::instance()->object($result);
        } else {
            Output::instance()->resultCode(code_user_exist);
        }
    }


//ihziluoh添加发送消息
    public function userMessageSend($touser, $msgtype, $articles)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        if ($msgtype == 'mpnews') {
            WeixinApi::sendNews($touser, $articles, true);
        } else if ($msgtype == 'text') {
            WeixinApi::sendText($touser, $articles, true);
        }
    }

    //ihziluoh添加

    public function getUserLogByFromUserName($fromUserName, $order = "createTime", $orderBy = "desc", $startDate = '', $endDate = '', $start = 0, $limit = 25)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $UserLog = D("user_log");
        $where['webpage.fromUserName'] = $fromUserName;
        //时间检索
        if ($startDate != '' && $endDate != '') {
            $where['createTime'] = array(array('egt', $startDate), array('elt', $endDate));
        } else if ($startDate != '') {
            $where["createTime"] = array('egt', $startDate);
        } else if ($endDate != '') {
            $where["createTime"] = array('elt', $endDate);
        }

        $result = $UserLog->alias('webpage')->field("webpage.*,user.*,userinfo.*,webpage.`id`")->join("wx_" . $customerId . "_user user ON user.`userName` = webpage.`fromUserName`")->join("wx_" . $customerId . "_user_weixin_info userinfo ON user.`userName` = userinfo.`openid`")->where($where)->order("$order $orderBy")->limit("$start, $limit")->select();

// 		log::write("userLog sql:".$UserLog->getLastSql());
        $count = $UserLog->alias('webpage')->join("wx_" . $customerId . "_user user ON user.`userName` = webpage.`fromUserName`")->where($where)->count();
        //echo $UserLog->getLastSql();
        if ($result) {
            Output::instance()->objArray($result, $count);
        } else {
            Output::instance()->resultCode(code_not_exist);
        }
    }

    //标签分组设置
    public function getGroupByTag($start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer($customerId);
        $groupTag = D("user_tag_group");
        $arr = $groupTag->alias("a")
            ->join("inner join wx_" . $customerId . "_user_weixin_group b on a.groupId=b.group_id")
            ->join("wx_module_product_tag c on a.tagId=c.id")
            ->join("wx_micontent_tag d on a.tagId=d.id")
            ->field("a.id,a.type,b.group_name,d.tagName,c.name,a.createTime")
            ->where("a.deleted=0")
            ->limit($start, $limit)
            ->select();
        if ($arr) {
            $count = $groupTag->alias("a")
                ->join("inner join wx_" . $customerId . "_user_weixin_group b on a.groupId=b.group_id")
                ->where("a.deleted=0")->count();
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode();
        }

    }

    //删除标签自动分组
    public function delTagGroup($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer($customerId);
        $groupTag = D("user_tag_group");
        $result = $groupTag->where("id=$id")->setField("deleted", 1);
        if ($result) {
            Output::instance()->resultCode();
        } else {
            Output::instance()->resultCode(code_sql_error);
        }

    }

    //获得标签分组设置
    public function getTagGroupById($id = null)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $productTag = M("module_product_tag");
        $contentTag = M("micontent_tag");
        Session::switchCustomer($customerId);
        $groupModel = D("user_weixin_group");
        $groupTag = D("user_tag_group");

        $groupList = $groupModel->select();
        if ($id) {
            $groupTagInfo = $groupTag->where("id=$id")->find();
            if ($groupTagInfo['type'] == 'product') {
                $groupTagInfo['tagName'] = $productTag->where("id=" . $groupTagInfo['tagId'])->getField("name");
            } else {
                $groupTagInfo['tagName'] = $contentTag->where("id=" . $groupTagInfo['tagId'])->getField("tagName");
            }
        }
        $result['groupList'] = $groupList;
        $result['groupTagInfo'] = $groupTagInfo;
        Output::instance()->object($result);

    }

    public function getProductTag($name = null, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $productTag = M("module_product_tag");
        Session::switchCustomer($customerId);
        $where['fromCustomerId'] = array("eq", $customerId);
        $where['name'] = array("like", "%$name%");
        $arr = $productTag->where($where)->field("id,name as tagName,picUrl")->limit($start, $limit)->select();
        if ($arr) {
            $count = $productTag->where($where)->count();
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode();
        }
    }

    public function getContentTag($name = null, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $contentTag = M("micontent_tag");
        Session::switchCustomer($customerId);
        $where['fromCustomerId'] = array("eq", $customerId);
        $where['tagName'] = array("like", "%$name%");
        $arr = $contentTag->where($where)->field("id,tagName,picUrl")->limit($start, $limit)->select();
        if ($arr) {
            $count = $contentTag->where($where)->count();
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode();
        }
    }

    //保存标签分组
    public function saveTagGroup($tagId, $groupId, $type, $id = null)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer($customerId);
        $groupTag = D("user_tag_group");

        $data['tagId'] = $tagId;
        $data['groupId'] = $groupId;
        $data['type'] = $type;
        $data['createTime'] = date("Y-m-d H:i:s");
        if ($id) {
            $result = $groupTag->where("id=$id")->save($data);
        } else {
            $validate = $groupTag->where("tagId=$tagId and deleted=0")->find();
            if ($validate) {
                Output::instance()->resultCode(1, "标签重复！");
                return;
            }
            $result = $groupTag->add($data);
        }
        if ($result) {
            Output::instance()->resultCode();
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 获取账号下默认自媒体的微信分组
     */
        function getDefaultUserGroup(){
        $retVal = Session::init();

        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return false;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $indMedia_tab = M('ind_media_info');
        Session::switchCustomer($cid);
        $wxGroup_tab = M('user_weixin_group');

        $groupList = $wxGroup_tab->alias('a')
            ->join('inner join wx_ind_media_info b on b.id=a.mediaId')
            ->where(['b.cid'=>$cid, 'b.deleted'=>0, 'b.isDefault'=>1])
            ->field('a.group_id as groupId, a.group_name as groupName')
            ->select();
        //var_dump($wxGroup_tab->getLastSql());exit;
        if($groupList){
            Output::instance()->object([
               'code'=>0,
                'results'=>$groupList
            ]);
            return;
        }
        Output::instance()->object([
            'code'=>1,
            'results'=>[]
        ]);
    }
}
